//
//  TeachViewController.m
//  Edumap
//
//  Created by 刘建峰 on 16/7/18.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "TeachViewController.h"
#import "TeachCollectionViewCell.h"
#import "MessageCenterViewController.h"
#import "AgencyDetailsViewController.h"
#import "ListInstitutionsViewController.h"
#import "CourseDetailsViewController.h"
#import "AdverDetailViewController.h"
#import "RecommendCollectionViewCell.h"

#import "TrainingSearchViewController.h"
static NSString *cellIdentifier = @"RecommendCollectionViewCell";
static NSString *CellIdentifier = @"TeachCollectionViewCell";

@interface TeachViewController ()
<UICollectionViewDataSource,UICollectionViewDelegate,BestScrollViewDelegate,BestScrollViewDatasource,UIScrollViewDelegate,UITextFieldDelegate,CLLocationManagerDelegate,UIAlertViewDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UIScrollView *scroview;
@property (strong, nonatomic) IBOutlet UILabel *regionLabel;
@property (strong, nonatomic) IBOutlet UILabel *BGlabel;
@property (strong, nonatomic) IBOutlet UITextField *textField;
@property (strong, nonatomic) IBOutlet UILabel *messageLabel;
@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;
@property (nonatomic,strong)  BestScrollView *headerScroll;//滚动栏
@property (nonatomic,strong)  NSMutableArray  *imageArray;
@property (nonatomic,strong)  NSMutableArray  *courseArray;
@property (nonatomic,strong)  NSMutableArray  *recommendArray;
@property(nonatomic,assign)CGFloat offSet;
@property (weak, nonatomic) IBOutlet UICollectionView *recommendCollectionView;
@property(nonatomic,assign)BOOL ifFirst;
@property(nonatomic,strong)CLLocationManager * locationManger;

@end

@implementation TeachViewController

- (void)viewWillAppear:(BOOL)animated{
    _regionLabel.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"cityName"];

    if (_ifFirst == YES) {
        self.tabBarController.selectedIndex  = 2;
        _ifFirst = NO;

    }
    
    if ([Common getLoginStatus]) {
        _messageLabel.hidden = YES;
        [self getnoticeNum];
        
    } else {
        _messageLabel.hidden = YES;
    }
    [self getRecommendList];
    [self getAdvertiseBanner];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configurationNavigationAndTabbar];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getDatas) name:@"welcome" object:nil];

    _ifFirst = YES;
    _imageArray = [NSMutableArray array];
    _courseArray = [NSMutableArray array];
    _recommendArray = [NSMutableArray array];

    _pageNO = 1;
    [self initViewLayout];
    
}

- (void)getDatas{
    [self addRefreshing];
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroview];
    _scroview.frame = CGRectMake(0, 64*VerticalRatio(), 320*VerticalRatio(), 504*VerticalRatio());
    _scroview.contentSize = flexibleSize(CGSizeMake(0, 685), NO);
    _scroview.delegate = self;
    
    _textField.delegate = self;
    
    _collectionView.frame = CGRectMake(0, 404*VerticalRatio(), 320*VerticalRatio(), CGRectGetHeight(_collectionView.frame)-49);
    
    self.messageLabel.layer.masksToBounds = YES;
    self.messageLabel.layer.cornerRadius = 7*VerticalRatio();
    self.BGlabel.layer.masksToBounds = YES;
    self.BGlabel.layer.cornerRadius = 3*VerticalRatio();
    
    
    UICollectionViewFlowLayout *FlowLayout =[[UICollectionViewFlowLayout alloc]init];
    FlowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    FlowLayout.minimumInteritemSpacing = 0;
    FlowLayout.minimumLineSpacing = 0;
    self.recommendCollectionView.collectionViewLayout = FlowLayout;
    
    self.recommendCollectionView.userInteractionEnabled=YES;
    [self.recommendCollectionView registerNib:[UINib nibWithNibName:cellIdentifier bundle:nil] forCellWithReuseIdentifier:cellIdentifier];
    self.recommendCollectionView.dataSource = self;
    self.recommendCollectionView.delegate = self;
    
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    self.collectionView.collectionViewLayout = flowLayout;
    
    self.collectionView.userInteractionEnabled=YES;
    [self.collectionView registerNib:[UINib nibWithNibName:CellIdentifier bundle:nil] forCellWithReuseIdentifier:CellIdentifier];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    
    self.collectionView.backgroundColor = [UIColor whiteColor];

    
    
    
    //广告栏
    _headerScroll=[[BestScrollView alloc]  initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 160), NO)];
    [self.scroview addSubview:_headerScroll];
}

#pragma mark ==== UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self hideKeyBoard];
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"TeachStoryboard" bundle:nil];
    TrainingSearchViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"TrainingSearch"];
    page.serachStr = _textField.text;
    [[Common getNavigation] pushViewController:page];
    return YES;
}

#pragma mark - 地区
- (IBAction)region:(id)sender {
    UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"" message:@"是否请求定位?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alertView show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        [self startLocation];
    }
}
#pragma mark - 消息
- (IBAction)message:(id)sender {
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return;
    }
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"TeachStoryboard" bundle:nil];
    MessageCenterViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"MessageCenter"];
    page.unReadNum = [_messageLabel.text integerValue];

    [[Common getNavigation] pushViewController:page];
}

#pragma mark - 机构&&课程
- (IBAction)institutions:(UIButton *)sender {
    
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"TeachStoryboard" bundle:nil];
    ListInstitutionsViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"ListInstitutions"];
    if (sender.tag == 10) {
        //机构
        page.isListInstitutions = YES;
    } else if (sender.tag == 11) {
        //课程
        page.isListInstitutions = NO;
    }
    [[Common getNavigation] pushViewController:page];
}


#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.scroview.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.scroview.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self course];
        });
        
    }];
    // 马上进入刷新状态
    [self.scroview.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.courseArray.count == _totle) {
        [self.collectionView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self course];
        });
    }
    
}


#pragma mark - 获取推荐课程
-(void)course{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"1" forKey:@"recommended"];
    [dic setObject:[NSNumber numberWithInteger:_pageNO] forKey:@"page"];
    [dic setObject:[NSNumber numberWithInteger:PageSize] forKey:@"pageSize"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_mallGoodsRecommendList withHttpType:@"POST" withTag:JY_JY_mallGoodsRecommendList];
}


#pragma mark - 获取推荐机构
-(void)getRecommendList{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"2" forKey:@"mstoIsRecommend"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_mallStoreRecommendList withHttpType:@"POST" withTag:JY_JY_mallStoreRecommendList];
}

#pragma mark  获取首页广告BANNER--=========================================
-(void)getAdvertiseBanner{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"3" forKey:@"Id"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_queryAdvertismentById withHttpType:@"POST" withTag:JY_JY_queryAdvertismentById];
}


#pragma mark === 获取未读信息数量
- (void)getnoticeNum{

    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msceMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_unreadInformation withHttpType:@"POST" withTag:JY_JY_unreadInformation];
}





#pragma  mark BestView Delegate Data=source=====================


- (NSInteger)numberOfPages
{
    
    return  self.imageArray.count;
    
}

- (UIView *)pageAtIndex:(NSInteger)index
{
    
    if (self.imageArray.count>0) {
        
        UIImageView  *imageView=[[UIImageView alloc]  initWithFrame: flexibleFrame(CGRectMake(0, 0, 320, 160), NO)];
        [imageView  sd_setImageWithURL:[NSURL URLWithString: [NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,_imageArray[index][@"titleimg"]]] placeholderImage:[UIImage imageNamed:@"school1"]];
        return imageView;
    }
    return nil;
}


- (void)didClickPage:(BestScrollView *)csView atIndex:(NSInteger)index
{
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"SchoolStoryboard" bundle:nil];
    AdverDetailViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"AdverDetail"];
 page.adverId = [NSString stringWithFormat:@"%@",_imageArray[index][@"id"]];
    [[Common getNavigation] pushViewController:page];
}


#pragma mark  ==== scroViewDelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == _collectionView || scrollView== _scroview) {
        _offSet = scrollView.contentOffset.y;
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (scrollView == _collectionView || scrollView == _scroview ) {
        if (scrollView.contentOffset.y>_offSet) {
            
            [_scroview setContentOffset:CGPointMake(0, 230*VerticalRatio()) animated:YES];
//            if(_collectionView.contentSize.height>_collectionView.frame.size.height){
//                _scroview.scrollEnabled = NO;
//            }
            _collectionView.scrollEnabled = YES;
        }else{
            if (scrollView == _scroview) {
                [_scroview setContentOffset:CGPointMake(0, 0) animated:YES];
                _scroview.scrollEnabled = YES;
                _collectionView.scrollEnabled = NO;
            }else{
                if (decelerate == YES) {
                    [_scroview setContentOffset:CGPointMake(0, 0) animated:YES];
                    _scroview.scrollEnabled = YES;
                    _collectionView.scrollEnabled = NO;
                }
            }
            
        }
    }
}

#pragma mark -- coreLocation

- (void)startLocation{
    
    // 判断定位操作是否被允许
    
    if([CLLocationManager locationServicesEnabled]) {
        
        _locationManger = [[CLLocationManager alloc] init];
        _locationManger.delegate = self;
        _locationManger.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManger.distanceFilter = 5.0f;
        // 总是授权
        [_locationManger requestAlwaysAuthorization];
        if ([[[UIDevice currentDevice] systemVersion] floatValue]>=8) {
            [_locationManger requestWhenInUseAuthorization];//使用程序其间允许访问位置数据（iOS8定位需要）
            [_locationManger requestAlwaysAuthorization];
        }
        [_locationManger startUpdatingLocation];
        
        
    }else {
        
        //提示用户无法进行定位操作
        
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"定位不成功 ,请确认开启定位" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        
        [alertView show];
        
    }
    // 开始定位
    [_locationManger startUpdatingLocation];
}


- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        for (CLPlacemark * placemark in placemarks) {
            
            NSDictionary *test = [placemark addressDictionary];
            //  Country(国家)  State(城市)  SubLocality(区)
            NSString * cityName = test[@"SubLocality"];
            _regionLabel.text = cityName;
            [[NSUserDefaults standardUserDefaults]setObject:cityName forKey:@"cityName"];
        }
    }];
    [_locationManger stopUpdatingLocation];
}


#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView == _collectionView) {
        return self.courseArray.count;
    }else{
        return _recommendArray.count;
    }
    
    
}
//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == _collectionView) {
        return CGSizeMake(160*VerticalRatio(), 155*VerticalRatio());
    }else{
        return CGSizeMake(98*VerticalRatio(), 98*VerticalRatio());
    }
    
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0,0, 0, 0);
    
}
//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == _collectionView) {

    TeachCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    
    NSString *imageStr = [NSString stringWithFormat:@"%@",self.courseArray[indexPath.row][@"mgooImage"]];
    if (imageStr && imageStr.length>0 && ![self.courseArray[indexPath.row][@"mgooImage"] isEqual:[NSNull null]]) {
        [cell.image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,imageStr]]];
    }
    cell.titleLabel.text = [NSString stringWithFormat:@"%@",self.courseArray[indexPath.row][@"mgooName"]];
    cell.detailLabel.text = [NSString stringWithFormat:@"%@",self.courseArray[indexPath.row][@"mgooContext"]];
    return cell;
    }else{
      RecommendCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
        NSString * image= [NSString stringWithFormat:@"%@",_recommendArray[indexPath.row][@"mstoImage"]];
        if (image.length>0) {
            [cell.recommendImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
        }
        
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == _collectionView) {
        //课程详情
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"TeachStoryboard" bundle:nil];
        CourseDetailsViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"CourseDetails"];
        
        page.mgooId = [NSString stringWithFormat:@"%@",self.courseArray[indexPath.row][@"mgooId"]];
        page.mstoId = _courseArray[indexPath.row][@"mgooStoreId"];
        [[Common getNavigation] pushViewController:page];
  
    }else{
        //机构详情
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"TeachStoryboard" bundle:nil];
        AgencyDetailsViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"AgencyDetails"];
        
        page.mstoId = self.recommendArray[indexPath.row][@"mstoId"];
        page.backBlock = ^(){};
        [[Common getNavigation] pushViewController:page];
    }
    
    
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_scroview.header endRefreshing];
    [_collectionView.footer endRefreshing];
    if (tag==JY_JY_unreadInformation) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            _messageLabel.text = [NSString stringWithFormat:@"%@",database[@"result"][@"noReadNum"]];
            _messageLabel.hidden = NO;
            if ([_messageLabel.text isEqualToString:@"0"]) {
                _messageLabel.hidden = YES;
            }
        }
        
    }else if (tag == JY_JY_queryAdvertismentById){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
        }else {
            self.imageArray = database[@"result"];
            if (_imageArray.count>0) {
                self.headerScroll.delegate=self;
                self.headerScroll.datasource=self;
                [self.headerScroll showImageArray:self.imageArray   withAnimation:YES];
            }
        }
    } else if (tag == JY_JY_mallGoodsRecommendList){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.collectionView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.collectionView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.courseArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"rows"];
                for (id entity in arr) {
                    [self.courseArray addObject:entity];
                }
                [_collectionView reloadData];
                
            });

        }
    }else if (tag == JY_JY_mallStoreRecommendList){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            _recommendArray = database[@"result"][@"rows"];
            [_recommendCollectionView reloadData];
        }
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    [_scroview.header endRefreshing];
    [_collectionView.footer endRefreshing];
    [self dismissWaitDialog];
}





@end
